package com.lsh.ofc.proxy.service;

import com.alibaba.fastjson.JSON;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.ofc.proxy.util.HttpClientUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商城服务代理
 *
 * @author peter
 * @date 19/4/15
 */
@Service
public class MisServiceProxy {

    private final Logger logger = Logger.getLogger(this.getClass());

    @Value("${mis.server.path}")
    private String misServerPath;

    private static final String PUSH_BOX_INFO_URI = "/order/Package/setParams";


    private Header[] buildHeaders() {

        Header[] headers = {new BasicHeader("api-version", "1.1"), new BasicHeader("platform", "ofc"), new BasicHeader("sign", "md5")};
        return headers;
    }

    /**
     * 根据商品码集合获取商品信息集合
     *
     * @return
     * @throws BusinessException
     */
    public Boolean pushObdBoxInfo2mis(List<BasicNameValuePair> pairs) throws BusinessException {
        String uri = this.misServerPath + PUSH_BOX_INFO_URI;

        if(pairs.size() <= 1){
            return true;
        }

        logger.info("PUSH_BOX_INFO_URI uri = " + uri + " pairs is " + JSON.toJSONString(pairs));
        HttpEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
        String result = HttpClientUtils.post(uri, entity, this.buildHeaders()).getData();
        Integer ret = JSON.parseObject(result).getInteger("ret");

        if (null == ret || ret != 0) {
            logger.error("商品信息不存在！goodsCodes=");
            return false;
        }

        return true;
    }
}
